package ui;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.SpannableString;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cn.bmob.im.BmobDownloadManager;
import cn.bmob.im.BmobUserManager;
import cn.bmob.im.bean.BmobMsg;
import cn.bmob.im.config.BmobConfig;
import cn.bmob.im.inteface.DownloadListener;

import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.example.lets.ChatActivity;
import com.example.lets.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;


/** ����������
  * @ClassName: MessageChatAdapter
  * @Description: TODO
  * @author smile
  * @date 2014-5-28 ����5:34:07
  */
@SuppressLint("InflateParams")
public class MessageChatAdapter extends BaseListAdapter<BmobMsg> {

	//8��Item������
	//�ı�
	private final int TYPE_RECEIVER_TXT = 0;
	private final int TYPE_SEND_TXT = 1;
	//ͼƬ
	private final int TYPE_SEND_IMAGE = 2;
	private final int TYPE_RECEIVER_IMAGE = 3;
	//λ��
	private final int TYPE_SEND_LOCATION = 4;
	private final int TYPE_RECEIVER_LOCATION = 5;
	//����
	private final int TYPE_SEND_VOICE =6;
	private final int TYPE_RECEIVER_VOICE = 7;

	String currentObjectId = "";

	DisplayImageOptions options;

	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();

	public MessageChatAdapter(Context context,List<BmobMsg> msgList) {
		// TODO Auto-generated constructor stub
		super(context, msgList);
		currentObjectId = BmobUserManager.getInstance(context).getCurrentUserObjectId();

		options = new DisplayImageOptions.Builder()
//		.showImageForEmptyUri(R.drawable.ic_launcher)
//		.showImageOnFail(R.drawable.ic_launcher)
		.resetViewBeforeLoading(true)
		.cacheOnDisc(true)
		.cacheInMemory(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.considerExifParams(true)
		.displayer(new FadeInBitmapDisplayer(300))
		.build();
	}

	@Override
	public int getItemViewType(int position) {
		BmobMsg msg = list.get(position);
		if(msg.getMsgType()==BmobConfig.TYPE_IMAGE){
			return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_IMAGE: TYPE_RECEIVER_IMAGE;
		}else if(msg.getMsgType()==BmobConfig.TYPE_LOCATION){
			return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_LOCATION: TYPE_RECEIVER_LOCATION;
		}else if(msg.getMsgType()==BmobConfig.TYPE_VOICE){
			return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_VOICE: TYPE_RECEIVER_VOICE;
		}else{
		    return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_TXT: TYPE_RECEIVER_TXT;
		}
	}

	@Override
	public int getViewTypeCount() {
		return 8;
	}

	private View createViewByType(BmobMsg message, int position) {
		int type = message.getMsgType();
			return getItemViewType(position) == TYPE_RECEIVER_TXT ?
					mInflater.inflate(R.layout.item_chat_received_message, null)
					:
					mInflater.inflate(R.layout.item_chat_sent_message, null);
	}

	@Override
	public View bindView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final BmobMsg item = list.get(position);
		if (convertView == null) {
			convertView = createViewByType(item, position);
		}
		//�ı�����
		final ImageView iv_avatar = ViewHolder.get(convertView, R.id.iv_avatar);
		final ImageView iv_fail_resend = ViewHolder.get(convertView, R.id.iv_fail_resend);//ʧ���ط�
		final TextView tv_send_status = ViewHolder.get(convertView, R.id.tv_send_status);//����״̬
		TextView tv_time = ViewHolder.get(convertView, R.id.tv_time);
		TextView tv_message = ViewHolder.get(convertView, R.id.tv_message);

		final ProgressBar progress_load = ViewHolder.get(convertView, R.id.progress_load);//������



		//���ͷ������������
		String avatar = item.getBelongAvatar();
		if(avatar!=null && !avatar.equals("")){//����ͷ��-Ϊ�˲�ÿ�ζ�����ͷ��
			String fileName = avatar;
			String cacheDownloadPath = BmobPro.getInstance(mContext).getCacheDownloadDir() + "/" + fileName;
			String[] name = fileName.split("\\.");
			String newFileName = name[0] + "_1_200_0_100." + name[1];
			String cacheThumbnailPath = BmobPro.getInstance(mContext).getCacheThumbnailDir() + "/" + newFileName;

			if ((new File(cacheDownloadPath)).exists()) {

				if ((new File(cacheThumbnailPath)).exists()) {

					Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
					iv_avatar.setImageBitmap(bm);

				} else {

					BmobProFile.getInstance(mContext).getLocalThumbnail(cacheDownloadPath, 1, new LocalThumbnailListener() {

						@Override
						public void onSuccess(String thumbnailPath) {
							Log.i("bmob", "localThumbnail--> :" + thumbnailPath);
							Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
							iv_avatar.setImageBitmap(bm);
						}

						@Override
						public void onError(int statuscode, String errormsg) {
							Log.i("bmob", "localThumbnail--> :" + statuscode + "," + errormsg);
						}
					});

				}

			} else {

				BmobProFile.getInstance(mContext).download(fileName, new com.bmob.btp.callback.DownloadListener() {

					@Override
					public void onSuccess(String fullPath) {
						Log.i("bmob", "���سɹ���" + fullPath);
						BmobProFile.getInstance(mContext).getLocalThumbnail(fullPath, 1, new LocalThumbnailListener() {

							@Override
							public void onSuccess(String thumbnailPath) {
								Log.i("bmob", "localThumbnail-->���ɺ������ͼ·�� :" + thumbnailPath);
								Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
								iv_avatar.setImageBitmap(bm);
							}

							@Override
							public void onError(int statuscode, String errormsg) {
								Log.i("bmob", "localThumbnail-->��������ͼʧ�� :" + statuscode + "," + errormsg);
							}
						});
						String str = BmobPro.getInstance(mContext).getCacheDownloadDir();
						Log.i("bmob", str);
					}

					@Override
					public void onProgress(String localPath, int percent) {
						Log.i("bmob", "download-->onProgress :" + percent);
					}

					@Override
					public void onError(int statuscode, String errormsg) {
						Log.i("bmob", "���س���" + statuscode + "--" + errormsg);
					}
				});
			}

			//ImageLoader.getInstance().displayImage(avatar, iv_avatar, util.ImageLoadOptions.getOptions(),animateFirstListener);
		}else{
			iv_avatar.setImageResource(R.drawable.head);
		}



		tv_time.setText(util.TimeUtil.getChatTime(Long.parseLong(item.getMsgTime())));

		if(getItemViewType(position)==TYPE_SEND_TXT
				||getItemViewType(position)==TYPE_SEND_LOCATION
				||getItemViewType(position)==TYPE_SEND_VOICE){//ֻ���Լ����͵���Ϣ�����ط�����
			//״̬����
			if(item.getStatus()==BmobConfig.STATUS_SEND_SUCCESS){//���ͳɹ�
				progress_load.setVisibility(View.INVISIBLE);
				iv_fail_resend.setVisibility(View.INVISIBLE);
				if(item.getMsgType()==BmobConfig.TYPE_VOICE){
					tv_send_status.setVisibility(View.GONE);
				}else{
					tv_send_status.setVisibility(View.VISIBLE);
					tv_send_status.setText("已发送");
				}
			}else if(item.getStatus()==BmobConfig.STATUS_SEND_FAIL){//����������Ӧ���߲�ѯʧ�ܵ�ԭ����ɵķ���ʧ�ܣ�����Ҫ�ط�
				progress_load.setVisibility(View.INVISIBLE);
				iv_fail_resend.setVisibility(View.VISIBLE);
				tv_send_status.setVisibility(View.INVISIBLE);

			}else if(item.getStatus()==BmobConfig.STATUS_SEND_RECEIVERED){//�Է��ѽ��յ�
				progress_load.setVisibility(View.INVISIBLE);
				iv_fail_resend.setVisibility(View.INVISIBLE);
				if(item.getMsgType()==BmobConfig.TYPE_VOICE){
					tv_send_status.setVisibility(View.GONE);
				}else{
					tv_send_status.setVisibility(View.VISIBLE);
					tv_send_status.setText("已阅读");
				}
			}else if(item.getStatus()==BmobConfig.STATUS_SEND_START){//��ʼ�ϴ�
				progress_load.setVisibility(View.VISIBLE);
				iv_fail_resend.setVisibility(View.INVISIBLE);
				tv_send_status.setVisibility(View.INVISIBLE);
			}
		}
		//����������ʾ����
		final String text = item.getContent();
		switch (item.getMsgType()) {
		case BmobConfig.TYPE_TEXT:
			try {
				SpannableString spannableString = util.FaceTextUtils
						.toSpannableString(mContext, text);
				tv_message.setText(spannableString);
			} catch (Exception e) {
			}
			break;


		case BmobConfig.TYPE_VOICE://������Ϣ
			try {
				if (text != null && !text.equals("")) {
//					tv_voice_length.setVisibility(View.VISIBLE);
					String content = item.getContent();
					if (!item.getBelongId().equals(currentObjectId)) {//���͵���Ϣ
					//�յ�����Ϣ
						boolean isExists = BmobDownloadManager.checkTargetPathExist(currentObjectId,item);
						if(!isExists){//��ָ����ʽ��¼���ļ������ڣ�����Ҫ���أ���Ϊ���ļ��Ƚ�С���ʷ��ڴ�����
							String netUrl = content.split("&")[0];
//							final String length = content.split("&")[1];
							BmobDownloadManager downloadTask = new BmobDownloadManager(mContext,item,new DownloadListener() {

								@Override
								public void onStart() {
									// TODO Auto-generated method stub
									progress_load.setVisibility(View.VISIBLE);
								}

								@Override
								public void onSuccess() {
									// TODO Auto-generated method stub
									progress_load.setVisibility(View.GONE);
								}
								@Override
								public void onError(String error) {
									// TODO Auto-generated method stub
									progress_load.setVisibility(View.GONE);
								}
							});
							downloadTask.execute(netUrl);
						}
					}
				}

			} catch (Exception e) {
			}
			break;
		default:
			break;
		}
		return convertView;
	}


	private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}

}
